package com.lancoo.znbkxx.teacher.model.api

import android.util.Base64
import android.util.Log
import com.lancoo.znbkxx.teacher.utils.ZLibUtils
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException


/**
 * @author : Admin
 * @date   : 2019/8/15 17:19
 * @desc   :
 */
class LogInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        val request = chain.request().newBuilder()
                .addHeader("Content-Type", "application/json; charset=utf-8").build()
        val startTime = System.currentTimeMillis()
        val response = chain.proceed(chain.request())
        val responseBody = response.body
        var respBody = ""
        if (responseBody != null) {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer

            var charset = Charset.forName("UTF-8")
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(Charset.forName("UTF-8"))
                } catch (e: UnsupportedCharsetException) {
                    e.printStackTrace()
                }
            }
            respBody = buffer.clone().readString(charset)
        }
//        val buffer = Base64.decode(respBody, Base64.DEFAULT)
//        val responseStr = String(ZLibUtils.decompress(respBody))
        val endTime = System.currentTimeMillis()
        val duration = endTime - startTime
        val mediaType = response.body!!.contentType()
        val method = request.method
        if ("POST" == method) {
            val sb = StringBuilder()
            if (request.body is FormBody) {
                val body = request.body as FormBody
                for (i in 0 until body.size) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",")
                }
                sb.delete(sb.length - 1, sb.length)
                Log.d(TAG, "| RequestParams:{$sb}")
            }
        }
        Log.d(TAG, "| Response:$respBody")
        Log.d(TAG, "----------End:" + duration + "毫秒----------")
        return response.newBuilder()
                .body(respBody.toResponseBody(mediaType))
                .build()
    }

    companion object {

        var TAG = "LogInterceptor"
    }
}